import 'package:flutter/material.dart';

class TitleInput extends StatefulWidget {
  final TextEditingController controller;
  final int maxLength;
  final VoidCallback? onChanged;
  final FocusNode? focusNode;
  final FocusNode? descriptionFocusNode;

  const TitleInput({
    Key? key,
    required this.controller,
    required this.maxLength,
    this.onChanged,
    this.focusNode,
    this.descriptionFocusNode,
  }) : super(key: key);

  @override
  State<TitleInput> createState() => _TitleInputState();
}

class _TitleInputState extends State<TitleInput> {
  int currentLength = 0;

  @override
  void initState() {
    super.initState();
    currentLength = widget.controller.text.length;
    widget.controller.addListener(_updateLength);
  }

  @override
  void dispose() {
    widget.controller.removeListener(_updateLength);
    super.dispose();
  }

  void _updateLength() {
    final newLength = widget.controller.text.length;
    if (newLength != currentLength && mounted) {
      setState(() {
        currentLength = newLength;
      });
      // 只有在真正需要时才调用父组件的onChanged
      widget.onChanged?.call();
    }
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextField(
            controller: widget.controller,
            focusNode: widget.focusNode,
            style: TextStyle(color: Colors.white),
            decoration: InputDecoration(
              hintText: 'Add Title',
              hintStyle: TextStyle(color: Colors.grey),
              border: InputBorder.none,
            ),
            maxLength: widget.maxLength,
            textInputAction: TextInputAction.next,
            keyboardAppearance: Brightness.dark,
            onSubmitted: (value) {
              if (widget.descriptionFocusNode != null) {
                widget.descriptionFocusNode!.requestFocus();
              } else {
                FocusScope.of(context).nextFocus();
              }
            },
            buildCounter: (context,
                {required currentLength, required isFocused, maxLength}) {
              return Text(
                '$currentLength/$maxLength',
                style: TextStyle(color: Colors.grey, fontSize: 12),
              );
            },
          ),
        ],
      ),
    );
  }
}
